package com.atguigu.dga230301.governance.assess.calc;

import com.atguigu.dga230301.ds.bean.TDsTaskInstance;
import com.atguigu.dga230301.ds.service.TDsTaskInstanceService;
import com.atguigu.dga230301.governance.assess.Assessor;
import com.atguigu.dga230301.governance.bean.AssessParam;
import com.atguigu.dga230301.governance.bean.GovernanceAssessDetail;
import com.atguigu.dga230301.meta.constant.MetaConst;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component("TASK_FAILED")
public class TaskFailedAssess  extends Assessor {
    @Autowired
    TDsTaskInstanceService tDsTaskInstanceService;

    @Override
    protected void assessor(GovernanceAssessDetail governanceAssessDetail, AssessParam assessParam) throws ParseException {
        //1.获取考评日期运行过的任务实例  2.当天考评的这个表的实例 3.任务失败

        String tableName = assessParam.getTableMetaInfo().getSchemaName() + "." + assessParam.getTableMetaInfo().getTableName();
        //方案一：
/*        List<TDsTaskInstance> tDsTaskInstanceList = tDsTaskInstanceService.list(new QueryWrapper<TDsTaskInstance>()
                .eq("date_format(start_time,'%Y-%m-%d')", assessParam.getAssessDate())
                .eq("name", assessParam.getTableMetaInfo().getSchemaName() + "." + assessParam.getTableMetaInfo().getTableName())
                .eq("state", 6)
        );*/

        //方案二
        /*ArrayList<TDsTaskInstance> tDsTaskInstancesFailedList = new ArrayList<>();
        List<TDsTaskInstance> tDsTaskInstanceListByDt = assessParam.getTDsTaskInstanceList();
        for (TDsTaskInstance tDsTaskInstance : tDsTaskInstanceListByDt) {
            if (tDsTaskInstance.getName().equals(tableName)&&(int)tDsTaskInstance.getState()== MetaConst.TASK_STATE_FAILED){
                tDsTaskInstancesFailedList.add(tDsTaskInstance);
            }
        }*/

        //方案三：使用流式API
        List<TDsTaskInstance> tDsTaskInstanceListByDt = assessParam.getTDsTaskInstanceList();
        List<TDsTaskInstance> tDsTaskInstancesFailedList = tDsTaskInstanceListByDt.stream().filter(tDsTaskInstance -> tDsTaskInstance.getName().equals(tableName) && (int) tDsTaskInstance.getState() == MetaConst.TASK_STATE_FAILED).collect(Collectors.toList());


        //如果最终过滤后的集合中还有元素，证明任务失败
        if (tDsTaskInstancesFailedList.size()>0){
            governanceAssessDetail.setAssessScore(BigDecimal.ZERO);
            governanceAssessDetail.setAssessProblem("任务失败");
        }
    }
}
